//
//  P2PExampleViewController.m
//  P2PExample
//

#import "P2PExampleViewController.h"

@implementation P2PExampleViewController

- (void)sendChatText:(NSString *)newText {
	NSData *sendData = [newText dataUsingEncoding:NSUTF8StringEncoding];
	[mySession sendDataToAllPeers:sendData withDataMode:GKSendDataReliable error:nil];
	myTextView.text = [NSString stringWithFormat:@"%@\n[ME]:%@",
					   myTextView.text, newText];
}

- (void)buttonClick:(id)sender {
	[self sendChatText:myTextField.text];
	[myTextField setText:@""];
}

- (void)createUI {
	
	myTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 180)];
	[myTextView setEditable:NO];
	[self.view addSubview:myTextView];
	
	myTextField = [[UITextField	alloc] initWithFrame:CGRectMake(10, 200, 230, 30)];
	myTextField.borderStyle = UITextBorderStyleRoundedRect;
	[self.view addSubview:myTextField];
	
	UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[myButton setFrame:CGRectMake(250, 200, 60, 32)];
	[myButton setTitle:@"Send" forState:UIControlStateNormal];
	[myButton addTarget:self action:@selector(buttonClick:)
	   forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:myButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self createUI];
	myPicker = [[GKPeerPickerController alloc] init];
	myPicker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
	myPicker.delegate = self;
	[myPicker show];
}

- (GKSession *)peerPickerController:(GKPeerPickerController *)pck
		   sessionForConnectionType:(GKPeerPickerConnectionType)ct {
	mySession = [[GKSession alloc] initWithSessionID:@"p2ptest"
										 displayName:nil
										 sessionMode:GKSessionModePeer];
	mySession.delegate = self;
	return mySession;
}

- (void)session:(GKSession *)session peer:(NSString *)peerID
 didChangeState:(GKPeerConnectionState)state {
	switch (state) {
		case GKPeerStateConnected:
			[mySession setDataReceiveHandler:self withContext:nil];
			[myPicker dismiss];
			[self sendChatText:@"connected"];
			break;
			
		case GKPeerStateDisconnected:
			break;

		default:
			break;
	}
}

- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer
		  inSession:(GKSession *)session context:(void *)ctx {
	NSString *receivedText = [[NSString alloc] initWithData:data
												   encoding:NSUTF8StringEncoding];
	NSString *peerName = [[NSString alloc]
						  initWithString:[session displayNameForPeer:peer]];
	myTextView.text = [NSString stringWithFormat:@"%@\n[%@]:%@",
					   myTextView.text, peerName, receivedText];
	
	[peerName release];
	[receivedText release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
	
	[myPicker release];
	[mySession release];
	
    [super dealloc];
}

@end
